﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using Microsoft.Advertising.Mobile.UI;
using Common.Library;
using OnlineVideos.ViewModels;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using System.Threading.Tasks;

namespace webslice
{
    public partial class PhotoChooser : PhoneApplicationPage
    {

        string SelectedImage = string.Empty;
        public PhotoChooser()
        {
            InitializeComponent();
            Loaded += PhotoChooser_Loaded;
        }

        void PhotoChooser_Loaded(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(SelectedImage))
            {
                BitmapImage bi = new BitmapImage();
                bi.CreateOptions = BitmapCreateOptions.None;
                bi.UriSource = new Uri(SelectedImage, UriKind.RelativeOrAbsolute);
                ImgZoom.Stretch = Stretch.Fill;
                LayoutRoot.Opacity = 5;
                ContentPanel.Width = ImgZoom.Width;
                ContentPanel.Height = ImgZoom.Height;
                ImgZoom.Source = bi;
            }
        }
        private double TotalImageScale = 1d;
        private Point ImagePosition = new Point(0, 0);
        private const double MAX_IMAGE_ZOOM = 5;
        private Point _oldFinger1;
        private Point _oldFinger2;
        private double _oldScaleFactor;
        BitmapImage image = new BitmapImage();

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
           
            NavigationContext.QueryString.TryGetValue("ImageSource", out SelectedImage);
          
        }
      
      
        private void Accept_Click(object sender, EventArgs e)
        {
            try
            {
                ClipRect.Visibility = System.Windows.Visibility.Collapsed;
                WriteBitmap(ContentPanel);
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream local = myIsolatedStorage.OpenFile("myImage.jpg", FileMode.Open, FileAccess.Read))
                    {
                        image.SetSource(local);
                    }
                }
                ImgZoom.Stretch = Stretch.UniformToFill;
                ImgZoom.Source = image;
                ResetImagePosition();
                ClipRect.Visibility = System.Windows.Visibility.Visible;
                 CreateCustomImage.createFrontImage(ResourceHelper.getShowTileImagePath((Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null ? Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1).ToString() + ".jpg"), this);
            }
            catch (Exception)
            {
            }
        }
       
        void WriteBitmap(FrameworkElement element)
        {
            WriteableBitmap wBitmap = new WriteableBitmap(element, null);
            using (MemoryStream stream = new MemoryStream())
            {
                wBitmap.SaveJpeg(stream, (int)ContentPanel.RenderSize.Width, (int)ContentPanel.RenderSize.Height, 0, 100);
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (myIsolatedStorage.FileExists("myImage.jpg"))
                    {
                        myIsolatedStorage.DeleteFile("myImage.jpg");
                    }
                    using (IsolatedStorageFileStream local = myIsolatedStorage.CreateFile("myImage.jpg"))
                    {
                        local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                    }
                }

            }
        }


        #region Event handlers

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            _oldFinger1 = e.GetPosition(ImgZoom, 0);
            _oldFinger2 = e.GetPosition(ImgZoom, 1);
            _oldScaleFactor = 1;
        }


        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
            var scaleFactor = e.DistanceRatio / _oldScaleFactor;
            if (!IsScaleValid(scaleFactor))
                return;

            var currentFinger1 = e.GetPosition(ImgZoom, 0);
            var currentFinger2 = e.GetPosition(ImgZoom, 1);

            var translationDelta = GetTranslationDelta(
                currentFinger1,
                currentFinger2,
                _oldFinger1,
                _oldFinger2,
                ImagePosition,
                scaleFactor);

            _oldFinger1 = currentFinger1;
            _oldFinger2 = currentFinger2;
            _oldScaleFactor = e.DistanceRatio;

            UpdateImageScale(scaleFactor);
            UpdateImagePosition(translationDelta);
        }


        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            var translationDelta = new Point(e.HorizontalChange, e.VerticalChange);

            if (IsDragValid(1, translationDelta))
                UpdateImagePosition(translationDelta);
        }


        private void OnDoubleTap(object sender,Microsoft.Phone.Controls.GestureEventArgs e)
        {
            ResetImagePosition();
        }

        #endregion
        #region Utils

        private Point GetTranslationDelta(
            Point currentFinger1, Point currentFinger2,
            Point oldFinger1, Point oldFinger2,
            Point currentPosition, double scaleFactor)
        {
            var newPos1 = new Point(
             currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
             currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

            var newPos2 = new Point(
             currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
             currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

            var newPos = new Point(
                (newPos1.X + newPos2.X) / 2,
                (newPos1.Y + newPos2.Y) / 2);

            return new Point(
                newPos.X - currentPosition.X,
                newPos.Y - currentPosition.Y);
        }


        private void UpdateImageScale(double scaleFactor)
        {
            TotalImageScale *= scaleFactor;
            ApplyScale();
        }


        private void ApplyScale()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleX = TotalImageScale;
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleY = TotalImageScale;

        }

        private void UpdateImagePosition(Point delta)
        {
            var newPosition = new Point(ImagePosition.X + delta.X, ImagePosition.Y + delta.Y);

            if (newPosition.X > 0) newPosition.X = 0;
            if (newPosition.Y > 0) newPosition.Y = 0;

            if ((ImgZoom.ActualWidth * TotalImageScale) + newPosition.X < ImgZoom.ActualWidth)
                newPosition.X = ImgZoom.ActualWidth - (ImgZoom.ActualWidth * TotalImageScale);

            if ((ImgZoom.ActualHeight * TotalImageScale) + newPosition.Y < ImgZoom.ActualHeight)
                newPosition.Y = ImgZoom.ActualHeight - (ImgZoom.ActualHeight * TotalImageScale);

            ImagePosition = newPosition;

            ApplyPosition();
        }

        private void ApplyPosition()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateX = ImagePosition.X;
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateY = ImagePosition.Y;
        }


        private void ResetImagePosition()
        {
            TotalImageScale = 1;
            ImagePosition = new Point(0, 0);
            ApplyScale();
            ApplyPosition();
        }


        private bool IsDragValid(double scaleDelta, Point translateDelta)
        {
            if (ImagePosition.X + translateDelta.X > 0 || ImagePosition.Y + translateDelta.Y > 0)
                return false;

            if ((ImgZoom.ActualWidth * TotalImageScale * scaleDelta) + (ImagePosition.X + translateDelta.X) < ImgZoom.ActualWidth)
                return false;

            if ((ImgZoom.ActualHeight * TotalImageScale * scaleDelta) + (ImagePosition.Y + translateDelta.Y) < ImgZoom.ActualHeight)
                return false;

            return true;
        }


        private bool IsScaleValid(double scaleDelta)
        {
            return (TotalImageScale * scaleDelta >= 1) && (TotalImageScale * scaleDelta <= MAX_IMAGE_ZOOM);
        }

        #endregion
    }
}